package com.dingding.order.core.grab.biz.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.dto.AbstractResponse;
import com.dingding.common.core.base.dto.ResponseEntity;
import com.dingding.common.core.beans.UserTaxiOrdert;
import com.dingding.facade.user.service.order.ITaxiGrabOrderFacade;
import com.dingding.order.code.GrabOrderCodeMsg;
import com.dingding.order.code.order.OrderStatus;
import com.dingding.order.core.grab.biz.IGrabOrderService;
import com.dingding.order.core.grab.biz.INoticeUserService;
import com.dingding.order.core.grab.dao.ITaxiGrabOrderDao;
import com.dingding.order.dto.grab.PushTaxiGrabOrder;
import com.dingding.order.dto.grab.ReqTaxiGrabOrderDTO;
import com.dingding.order.dto.grab.ResTaxiGrabOrderDTO;

/**
 * 
 * @ClassName: TaxiGrabOrderServiceImpl 
 * @Description: 出租车抢单业务逻辑实现类
 * @author YHQ
 * @date 2016年6月29日 下午2:17:29
 * @version V2.3.0
 * 
 */
@Component("taxiGrabOrderService")
public class TaxiGrabOrderServiceImpl extends AbstractResponse<ResTaxiGrabOrderDTO, ReqTaxiGrabOrderDTO> implements IGrabOrderService {

	private Logger log = Logger.getLogger(this.getClass());
	
	//出租车DAO接口
	@Resource(name="taxiGrabOrderDao")
	private ITaxiGrabOrderDao taxiGrabOrderDao;
	
	// 用户抢单通知接口(发送短信和推送消息)
	@Resource(name = "noticeUserService")
	private INoticeUserService noticeUserService;
	
	// 出租车抢单通知接口(发送短信和推送消息)
	@Resource(name = "taxiGrabOrderFacade")
	private ITaxiGrabOrderFacade taxiGrabOrderFacade;
	
	/**
	 * 
	 * @Title: taxiGrabOrder 
	 * @Description: 出租车抢单总方法
	 * @param object 出租车抢单请求Bean
	 * @author YHQ 
	 * @return String    返回类型
	 * @version V2.3.0
	 * 
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public String userGrabOrder(String requestData) {
		
		// 出租车抢单，响应客户端Bean
		ResponseEntity<ResTaxiGrabOrderDTO> response = new ResponseEntity<ResTaxiGrabOrderDTO>();
		
		// 出租车抢单，客户端请求参数
		ReqTaxiGrabOrderDTO reqTaxiGrabOrderDTO = super.parseRequestJson(requestData);
		
		// 验证客户端请求参数是否为空
		if(!super.validateParam(response, reqTaxiGrabOrderDTO)){
			return super.responseBeanToJson(response);
		}
		
		// 获取待抢单的出租车订单信息
		UserTaxiOrdert taxiOrdert = getTaxiOrdert(reqTaxiGrabOrderDTO.getOid(), response);
		
		// 该订单不存在的情况下，停止抢单操作，返回响应信息
		if(taxiOrdert == null){
			return super.responseBeanToJson(response);
		}
		
		// 判断是否符合抢单条件,不符合抢单条件，终止抢单，返回响应信息
		if(!taxiGrabConditions(reqTaxiGrabOrderDTO,taxiOrdert, response)){
			return super.responseBeanToJson(response);
		}
		
		// 抢单操作
		taxiGrabOrder(taxiOrdert, reqTaxiGrabOrderDTO,response);
		
		log.info("抢单结束，通知开始！");
		// 通知下单用户(发送短信、推送消息)
		this.grabNotice(taxiOrdert);
		
		log.info("通知结束！");
		
		return super.responseBeanToJson(response);
	}

	/**
	 * 
	 * @Title: geTaxiOrdert 
	 * @Description: 根据出租车订单Id获取订单信息 
	 * @param oid 订单Id
	 * @author YHQ 
	 * @return UserTaxiOrdert    返回类型
	 * @version V2.3.0
	 * 
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public UserTaxiOrdert getTaxiOrdert(String oid,ResponseEntity<ResTaxiGrabOrderDTO> response){
		
		//创建用于存储出租车订单的对象
		UserTaxiOrdert taxiOrdert = null;
		
		try {
			taxiOrdert = taxiGrabOrderDao.getById(oid);
		} catch (Exception e) {
			
			response.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
			response.setErrorMessage(GrabOrderCodeMsg.GET_TAXI_ORDER_INFO_ERROR); 
			response.setPromptMessage(GrabOrderCodeMsg.GET_TAXI_ORDER_INFO_ERROR_CLIENT);
			log.error("根据出租车订单Id获取订单信息时出现异常   类："+this.getClass()+" geTaxiOrdert()", e);
			return taxiOrdert;
		}
		
		//如果订单不存在，则给出相应的错误信息
		if(taxiOrdert == null){
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(GrabOrderCodeMsg.ORDER_NOT_EXISTS);
			response.setPromptMessage(GrabOrderCodeMsg.ORDER_NOT_EXISTS);
		}
		
		return taxiOrdert;
	}
	
	/**
	 * 
	 * @Title: taxiGrabConditions 
	 * @Description: 验证出租车抢单添加
	 * @param reqTaxiGrabOrderDTO 出租车抢单-客户端请求Bean
	 * @param taxiOrdert 出租车订单信息
	 * @param response 响应Bean
	 * @author YHQ 
	 * @return boolean    返回类型
	 * @version V2.3.0
	 * 
	 */
	@Transactional(readOnly=true)
	public boolean taxiGrabConditions(ReqTaxiGrabOrderDTO reqTaxiGrabOrderDTO,UserTaxiOrdert taxiOrdert,ResponseEntity<ResTaxiGrabOrderDTO> response){
		
		//该订单不是待抢单状态，返回相应的错误信息
		if(taxiOrdert.getOrderStatus() != OrderStatus.ORDER_STATUS_WAITING ){
			
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(GrabOrderCodeMsg.ORDER_NOT_WAIT_GRAB);
			response.setPromptMessage(GrabOrderCodeMsg.ORDER_NOT_WAIT_GRAB);
			
			return false;
		}
		
		//获取用户未完成出租车订单
		List<UserTaxiOrdert> taxiOrderts = geTaxiOrderts(reqTaxiGrabOrderDTO.getUserId(), response);
		
		//存在未完成订单，终止抢单操作
		if(taxiOrderts != null && taxiOrderts.size() > 0){
			return false;
		}
		
		return true;
	}
	
	/**
	 * 
	 * @Title: geTaxiOrderts 
	 * @Description: 根据用户Id获取未完成订单
	 * @param userId 用户Id
	 * @author YHQ 
	 * @return List<UserTaxiOrdert>    返回类型
	 * @version V2.3.0
	 * 
	 */
	public List<UserTaxiOrdert> geTaxiOrderts(String userId,ResponseEntity<ResTaxiGrabOrderDTO> response){
		
		//创建用于存储该用户未完成订单列表的对象
		List<UserTaxiOrdert> taxiOrderts = null;
		
		//添加查询当前用户未完成出租车订单的条件
		Criterion criterion = Restrictions.eq("grabOrderUserId", userId);
		
		try {
			
			taxiOrderts = taxiGrabOrderDao.queryCriteriaList(criterion);
		} catch (Exception e) {
			response.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
			response.setErrorMessage(GrabOrderCodeMsg.GET_NOT_COMPLETE_TAXI_ORDER);
			response.setPromptMessage(GrabOrderCodeMsg.GET_TAXI_ORDER_INFO_ERROR_CLIENT);
			log.error("出租车抢单-获取用户未完成订单时出现异常   类："+this.getClass()+" geTaxiOrderts()", e);
			return taxiOrderts;
		}
		
		// 当前用户存在未完成订单，返回相应的错误信息
		if(taxiOrderts != null && taxiOrderts.size() > 0){
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(GrabOrderCodeMsg.EXISTS_NOT_COMPLETED_ORDER);
			response.setPromptMessage(GrabOrderCodeMsg.EXISTS_NOT_COMPLETED_ORDER);
		}
		
		return taxiOrderts;
	}
	
	/**
	 * 
	 * @Title: taxiGrabOrder 
	 * @Description: 出租车抢单操作
	 * @param taxiOrdert	出租车订单信息
	 * @param reqTaxiGrabOrderDTO 客户端请求Bean
	 * @author YHQ 
	 * @return void    返回类型
	 * @version V2.3.0
	 * 
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public void taxiGrabOrder(UserTaxiOrdert taxiOrdert,ReqTaxiGrabOrderDTO reqTaxiGrabOrderDTO,ResponseEntity<ResTaxiGrabOrderDTO> response){
		
		taxiOrdert.setGrabOrderTime(new Date());	// 抢单时间
		taxiOrdert.setGrabOrderUserId(reqTaxiGrabOrderDTO.getUserId());	// 抢单人
		taxiOrdert.setOrderStatus(2); //2：服务中
		
		ResTaxiGrabOrderDTO resTaxiGrabOrderDTO = new ResTaxiGrabOrderDTO();
		
		//抢单时间
		resTaxiGrabOrderDTO.setGrabOrderTime(taxiOrdert.getGrabOrderTime());
		//订单Id
		resTaxiGrabOrderDTO.setOid(taxiOrdert.getTaxiOrdertId());
		//系统时间
		resTaxiGrabOrderDTO.setSystemTime(new Date());
		//订单状态
		resTaxiGrabOrderDTO.setOrderStatus(taxiOrdert.getOrderStatus());
		
		response.setCode(HttpStatus.SC_OK);
		response.setResponseBody(resTaxiGrabOrderDTO);
		
	}
	
	/**
	 * 
	 * @Title: grabNotice 
	 * @Description: 抢单通知(发送短信、推送消息) 
	 * @param userTaxiOrdert 待抢单的出租车订单信息
	 * @author YHQ 
	 * @version V2.3.0
	 * @return void    返回类型
	 * 
	 */
	@Transactional(readOnly=true)
	public void grabNotice(UserTaxiOrdert userTaxiOrdert){
		
		 // 获取通知内容(即 发送短信、推送消息内容)
		 PushTaxiGrabOrder pushTaxiGrabOrder = taxiGrabOrderFacade.getPushTaxiGrabOrder(userTaxiOrdert.getPlaceOrderUserId(), userTaxiOrdert.getGrabOrderUserId());
		
		 // 通知操作
		 if(pushTaxiGrabOrder != null){
			 
			 // 订单Id
			 pushTaxiGrabOrder.setOid(userTaxiOrdert.getTaxiOrdertId());
			 // 订单状态
			 pushTaxiGrabOrder.setOrderStatus(userTaxiOrdert.getOrderStatus());
			 // 抢单人
			 pushTaxiGrabOrder.setGrabOrderUserId(userTaxiOrdert.getGrabOrderUserId());
			 // 抢单时间
			 pushTaxiGrabOrder.setGrabOrderTime(userTaxiOrdert.getGrabOrderTime());
			 // 订单类型
			 pushTaxiGrabOrder.setPublishType(2);
			 
			 // 给乘客发短信
			 noticeUserService.sendTaxiMessage(pushTaxiGrabOrder.getAnotherPhoneNo(), 1);
			 
			 // 给乘客推送消息
			 noticeUserService.pushTaxiMessage(pushTaxiGrabOrder, 1);
			 
			 // 消息通知的
			 noticeUserService.pushTaxiNoticeMessage(pushTaxiGrabOrder, 1);
			 
		 }
		 
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public String driverGrabOrder(String requestData) {
		// 出租车抢单，响应客户端Bean
		ResponseEntity<ResTaxiGrabOrderDTO> response = new ResponseEntity<ResTaxiGrabOrderDTO>();

		// 出租车抢单，客户端请求参数
		ReqTaxiGrabOrderDTO reqTaxiGrabOrderDTO = super.parseRequestJson(requestData);

		// 验证客户端请求参数是否为空
		if (!super.validateParam(response, reqTaxiGrabOrderDTO)) {
			return super.responseBeanToJson(response);
		}

		// 获取待抢单的出租车订单信息
		UserTaxiOrdert taxiOrdert = getTaxiOrdert(reqTaxiGrabOrderDTO.getOid(), response);

		// 该订单不存在的情况下，停止抢单操作，返回响应信息
		if (taxiOrdert == null) {
			return super.responseBeanToJson(response);
		}

		// 判断是否符合抢单条件,不符合抢单条件，终止抢单，返回响应信息
		if (!taxiGrabConditions(reqTaxiGrabOrderDTO, taxiOrdert, response)) {
			return super.responseBeanToJson(response);
		}

		// 抢单操作
		taxiGrabOrder(taxiOrdert, reqTaxiGrabOrderDTO, response);

		log.info("抢单结束，通知开始！");
		// 通知下单司机(发送短信、推送消息)
		this.grabDriverNotice(taxiOrdert);

		log.info("通知结束！");

		return super.responseBeanToJson(response);
	}
	
	/**
	 * 
	 * @Title: grabNotice 
	 * @Description: 抢单通知(发送短信、推送消息) 
	 * @param userTaxiOrdert 待抢单的出租车订单信息
	 * @author YHQ 
	 * @version V2.3.0
	 * @return void    返回类型
	 * 
	 */
	@Transactional(readOnly=true)
	public void grabDriverNotice(UserTaxiOrdert userTaxiOrdert){
		
		// 获取通知内容(即 发送短信、推送消息内容)
		PushTaxiGrabOrder pushTaxiGrabOrder = taxiGrabOrderFacade
				.getPushTaxiDriverGrabOrder(userTaxiOrdert.getPlaceOrderUserId(), userTaxiOrdert.getGrabOrderUserId());

		// 通知操作
		if (pushTaxiGrabOrder != null) {

			// 订单Id
			pushTaxiGrabOrder.setOid(userTaxiOrdert.getTaxiOrdertId());
			// 订单状态
			pushTaxiGrabOrder.setOrderStatus(userTaxiOrdert.getOrderStatus());
			// 抢单人
			pushTaxiGrabOrder.setGrabOrderUserId(userTaxiOrdert.getGrabOrderUserId());
			// 抢单时间
			pushTaxiGrabOrder.setGrabOrderTime(userTaxiOrdert.getGrabOrderTime());
			// 订单类型
			pushTaxiGrabOrder.setPublishType(2);

			// 给乘客发短信
			noticeUserService.sendTaxiMessage(pushTaxiGrabOrder.getAnotherPhoneNo(), 1);

			// 给乘客推送消息
			noticeUserService.pushTaxiMessage(pushTaxiGrabOrder, 1);

			// 消息通知的
			noticeUserService.pushTaxiNoticeMessage(pushTaxiGrabOrder, 1);

		}

	}
	
}
